The Basic Map of New Zealand

Here we create a basic map of New Zealand which can be zoomed in and out to display the small details of the area.

library(leaflet)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
nz_map <- leaflet() %>%
  addTiles() %>%
  setView(lng = 174.885971, lat = -40.900557, zoom = 5)

nz_map

Adding Markers to the Map

In the above map we created we are gonna add markers to mark the major cities in New Zealand such as Auckland, Wellington and Christchruch.

#Create New Zealand dataset.
nz_pop <- data.frame(
  city = c("Auckland", "Wellington", "Christchurch"),
  lat = c(-36.85102, -41.29352, -43.53305),
  lng = c(174.75796, 174.77760, 172.63093),
  population = c(1693000, 424000, 408000)
)

#Create New Zealand map with makers.
nz_map_pop <- leaflet(nz_pop) %>%
  addTiles() %>%
  setView(lng = 174.7633, lat = -40.900557, zoom = 5) %>%
  addMarkers(~lng, ~lat, popup = ~paste(city, "<br>Population:", population))

nz_map_pop

Creating the Leaflet Map and Add a Provider Tile

# Create the leaflet map
nz_map <- leaflet(nz_pop) %>%
  addTiles() %>%  # Basic tiles to render the map
  setView(lng = 174.7633, lat = -40.900557, zoom = 5) %>%  # Center on New Zealand
  addMarkers(~lng, ~lat, popup = ~paste(city, "<br>Population:", population)) %>%  # Add city markers
  addProviderTiles(providers$CartoDB.Positron)  # Use a clear and readable provider tile

# Display the map
nz_map

Creating Heatmap

Now we create heatmap depicting the population density of major cities in New Zealand.

library(leaflet)
library(leaflet.extras)

nz_map_heat <- leaflet(nz_pop) %>%
  addTiles() %>%
  setView(lng = 174.7633, lat = -40.900557, zoom = 5) %>%
  addHeatmap(lng = ~lng, lat = ~lat, intensity = ~population, blur = 20, max = 1, radius = 15)

nz_map_heat

Reading GeoJSON File.

library(sf)
## Linking to GEOS 3.11.2, GDAL 3.8.2, PROJ 9.3.1; sf_use_s2() is TRUE
nz_geo <- st_read("C:/Users/dell/Downloads/nz_ta.geojson")
## Reading layer `nz_ta' from data source `C:\Users\dell\Downloads\nz_ta.geojson' using driver `GeoJSON'
## Simple feature collection with 66 features and 5 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 166.4263 ymin: -47.29 xmax: 178.5768 ymax: -34.3926
## Geodetic CRS:  WGS 84

Creating Black and White Plot

Now we create a black and white map of the New Zealand territories.

library(ggplot2)
ggplot(nz_geo) +
  geom_sf() +
  theme_void()

Loading Population dataset

We now load the population csv file dataset.

#Loading the data.
population_data <- read.csv("C:/Users/dell/Downloads/nz_territory_2016_population.csv")

#Removing the unnecessary data points.
names(population_data) <- tolower(names(population_data))
str(population_data)
## 'data.frame':    67 obs. of  4 variables:
##  $ nz_territory                   : chr  "Far North District" "Whangarei District" "Kaipara District" "Auckland" ...
##  $ x2016_population               : int  62000 87700 21700 1614300 28400 19550 71200 34100 161200 51600 ...
##  $ x2016_population_change_number : int  700 1800 600 44400 600 450 1700 500 4400 1200 ...
##  $ x2016_population_change_percent: num  1.2 2 2.8 2.8 2.1 2.2 2.4 1.4 2.8 2.3 ...

Merging the Geospatial and Population Data.

library(sf)
library(dplyr)

# Perform a left join using dplyr
merged_data <- nz_geo %>%
  left_join(population_data, by = c("TA2016_NAM" = "nz_territory"))

# Check the result
print(merged_data)
## Simple feature collection with 66 features and 8 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: 166.4263 ymin: -47.29 xmax: 178.5768 ymax: -34.3926
## Geodetic CRS:  WGS 84
## First 10 features:
##    TA2016                 TA2016_NAM AREA_SQ_KM LAND_SQ_KM rmapshaperid
## 1     001         Far North District  6689.8397  6677.4102            0
## 2     002         Whangarei District  2711.7983  2711.7983            1
## 3     003           Kaipara District  3108.7123  3108.7123            2
## 4     011 Thames-Coromandel District  2207.0122  2207.0122            3
## 5     012           Hauraki District  1270.0486  1270.0486            4
## 6     013           Waikato District  4450.5915  4403.2417            5
## 7     015    Matamata-Piako District  1755.4338  1755.4338            6
## 8     016              Hamilton City   110.9364   110.3728            7
## 9     017             Waipa District  1470.0448  1470.0448            8
## 10    018        Otorohanga District  1999.1897  1999.1897            9
##    x2016_population x2016_population_change_number
## 1             62000                            700
## 2             87700                           1800
## 3             21700                            600
## 4             28400                            600
## 5             19550                            450
## 6             71200                           1700
## 7             34100                            500
## 8            161200                           4400
## 9             51600                           1200
## 10             9980                            270
##    x2016_population_change_percent                       geometry
## 1                              1.2 MULTIPOLYGON (((173.5798 -3...
## 2                              2.0 MULTIPOLYGON (((174.7021 -3...
## 3                              2.8 MULTIPOLYGON (((173.7648 -3...
## 4                              2.1 MULTIPOLYGON (((175.9267 -3...
## 5                              2.2 MULTIPOLYGON (((175.54 -37....
## 6                              2.4 MULTIPOLYGON (((175.2678 -3...
## 7                              1.4 MULTIPOLYGON (((175.8117 -3...
## 8                              2.8 MULTIPOLYGON (((175.3268 -3...
## 9                              2.3 MULTIPOLYGON (((175.6586 -3...
## 10                             2.7 MULTIPOLYGON (((174.8639 -3...
#Renaming Colunm names 
library(dplyr)

# Rename columns in merged_data
merged_data <- merged_data %>%
  rename(
    NZ_territory = TA2016_NAM,
    Population = x2016_population
  )

Creating the Basic Choropleth Map

Here we create the basic Choropleth Map.

ggplot(merged_data) +
  geom_sf(aes(fill = Population)) +
  theme_void()

Advanced Choropleth Map

Here we create more sophisticated Choropleth Map.

nz_plot <- ggplot(merged_data) +
  geom_sf(aes(fill = log(Population))) +
  scale_fill_viridis_c() +
  theme_void() +
  labs(
    title = "New Zealand Population by Territory",
    fill = "Population (Log Scale)"
  )

ggsave("nz_plot.png")
## Saving 7 x 5 in image

Extra for Experts

We are going to create a more interactive Choropleth Map using RColorBrewer and ploty packages.

#Loading packages
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(RColorBrewer)
library(sf)
library(dplyr)

#Defining Color palette
color_palette <- brewer.pal(9, "Blues")

merged_data$Population <- as.numeric(merged_data$Population)

# Create the interactive map
plot_ly(data = merged_data, 
        type = 'scattermapbox',
        mode = 'markers',
        color = ~Population,
        colors = color_palette,
        text = ~paste("Territory:", merged_data$NZ_territory, "<br>Population:", Population),
        hoverinfo = 'text',
        marker = list(size = 10, opacity = 1)) %>%
  layout(mapbox = list(style = 'open-street-map',
                       center = list(lon = 174.8860, lat = -40.9006),
                       zoom =3
                       ),
         title = 'Interactive Choropleth Map of New Zealand Population',
         coloraxis = list(colorbar = list(title = 'Population'))) %>%
  config(displayModeBar = TRUE)
## Warning: Only one fillcolor per trace allowed

## Warning: Only one fillcolor per trace allowed